package com.f.client;

import io.netty.channel.Channel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.f.javabean.PushMsg.Push;
import com.google.protobuf.ByteString;

public class ReadStream {

	private String id;
	private Push push;
	private String filePath;
	private Channel channel;
	
	public ReadStream(String id,Push push,String filePath,Channel channel){
		this.id = id;
		this.push = push;
		this.filePath = filePath;
		this.channel = channel;
	}

	public void runs(){
		if(push.getIsstart()){
			create();
		}else if(push.getIsing()){
			running();
		}else if(push.getIsend()){
			end();
		}
	}
	
	private void create(){
		try {
			File file = new File(filePath);
			if(file.exists()){
				file.delete();
			}
			boolean cb = file.createNewFile();
			if(cb){
				System.out.println("create file success");
				Push.Builder builder = Push.newBuilder();
				builder.setId(id);
				builder.setType("canrun");
				builder.setFilename(push.getFilename());
				channel.writeAndFlush(builder);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Push.Builder builder = Push.newBuilder();
			builder.setId(id);
			builder.setType("cantrun");
			channel.writeAndFlush(builder);
		}
	}
	
	private void running(){
		System.out.println("ing..."+push.getReadnum()+"%");
		File file = new File(filePath);
		FileOutputStream fos = null;
		try{
			ByteString byteString = push.getFbyte();
			byte[] bytes = new byte[1024];
			byteString.copyTo(bytes, 0);
			fos = new FileOutputStream(file,true);
			System.out.println(fos);
			fos.write(bytes);
			fos.flush();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(fos != null){
					fos.close();
					fos = null;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void end(){
		System.out.println("read end");
//		try {
//			if(fos != null ){
//				fos.close();
//				fos = null;
//			}
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Push getPush() {
		return push;
	}

	public void setPush(Push push) {
		this.push = push;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	
	
	
}
